package com.gxc.service.common.components.log.feign;

import com.gxc.service.common.model.constant.HeaderConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * feign调用设置请求头.
 *
 * @author GongXincheng
 * @since 2019-11-09 01:01
 */
@Slf4j
public class GlobalFeignInterceptor implements RequestInterceptor {

    @Value("${spring.application.name}")
    private String applicationName;

    /**
     * 此方式注入会报错：
     * No thread-bound request found: Are you referring to request attributes outside of an actual web request,
     * or processing a request outside of the originally receiving thread? If you are actually operating within
     * a web request and still receive this message, your code is probably running outside of DispatcherServlet:
     * In this case, use RequestContextListener or RequestContextFilter to expose the current request.
     */
    //@Resource
    private HttpServletRequest httpServletRequest;

    /**
     * RequestContextHolder.getRequestAttributes()该方法是从ThreadLocal变量里面取得相应信息的，
     * 当hystrix断路器的隔离策略为THREAD时（feign.hystrix.enabled: true），是无法取得ThreadLocal中的值。
     * <p>
     * feign 启用 Hystrix 时，因为默认的线程隔离策略，导致 LocalThread 失效，导致 RequestContextHolder.getRequestAttributes()
     * 返回 null。 使用该 bean 自定义隔离策略，防止失效。
     * <p>
     * 解决方案：
     * 1. hystrix隔离策略换为SEMAPHORE。
     * 2. 自定义策略，模仿Sleuth的trace传递。
     * <p>
     * 3（亲测）：
     * （1）：feign.hystrix.enabled: true
     * （2）：注册bean 自定义隔离策略 FeignHystrixConcurrencyStrategy
     */
    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String headerName = headerNames.nextElement();
                    template.header(headerName, request.getHeader(headerName));
                }

                // 除了本身的请求头之外还应该将requestId 和 当前的应用名称设置到requestHeader中
                // 注意：是从request域中获取（request.getAttribute）！不是从请求参数里获取（request.getParameter）！
                template.header(HeaderConstant.REQUEST_ID_HEADER, (String) request.getAttribute(HeaderConstant.REQUEST_ID_HEADER));
                template.header(HeaderConstant.FROM_SYSTEM_HEADER, applicationName);
            }
        } else {
            log.error("{} -> getRequestAttributes is null", this.getClass().getSimpleName());
        }
    }

}
